import React, { FC, useEffect, useState } from 'react'
import { Button, Form, Input, message, Radio } from 'antd'
import { addDatabase, detailDatabase, updateDatabase } from '@/services/database'
import TableList from '@pages/DatabaseConfig/components/TableList'
import { asyncDatabase } from '@/services/project'

const FormItem = Form.Item
const formTailLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 11 }
}
const tailLayout = {
  wrapperCol: { offset: 6, span: 13 }
}

interface DatabaseConfigFormProps {
  dbId:string,
  again:any,
}

const DatabaseConfigForm: FC<DatabaseConfigFormProps> = (props) => {

  const { dbId, again } = props
  const [form] = Form.useForm()
  const [detail, setDetail] = useState<any>({})
  const [visible,setVisible] = useState<boolean>(false);
  const [asyncDbLoading,setAsyncDbLoading] = useState<boolean>(false);

  useEffect(() => {
    if (dbId !== '0') {
      detailDatabase({ id: dbId }).then(res => {
        if (res.code === 10000) {
          setDetail(res.data)
          form.resetFields()
        }
      })
    }
  }, [dbId])

  const handleOk = () => {

    form.validateFields().then(res => {
      if (dbId === '0') {
        addDatabase(res).then(data => {
          if (data.code === 10000) {
            message.success('数据库添加成功');
            again();
          }
        })
      }else {
        res.id = dbId;
        updateDatabase(res).then(data => {
          if (data.code === 10000) {
            message.success('数据库修改成功');
            again();
          }
        })
      }
    })
  }

  const lookTableList = (flag:boolean) => {
    if (dbId === '0') {
      message.error("请先保存方法再查看！")
      return;
    }
    setVisible(flag)
  }

  const asyncDb = () => {
    if (dbId === '0') {
      message.error("请先保存方法再同步！")
      return;
    }
    setAsyncDbLoading(true);
    asyncDatabase({id:dbId}).then(res => {
      if (res.code === 10000) {
        message.success("数据库同步成功！")
      }else {
        message.error('数据库同步失败，请稍后再试！')
      }
      setAsyncDbLoading(false);
    })
  }

  return (
    <>
      <Form style={{ marginTop: 70 }} form={form} initialValues={detail} onFinish={() => handleOk()}>
        <FormItem {...formTailLayout} name="db_name" rules={[{ required: true, message: '请输入数据库名称' }]} label="数据库名称">
          <Input placeholder="请输入数据库名称"/>
        </FormItem>
        <FormItem {...formTailLayout} name="username" rules={[{ required: true, message: '请输入用户名' }]} label="用户名">
          <Input placeholder="请输入用户名"/>
        </FormItem>
        <FormItem {...formTailLayout} name="password" rules={[{ required: true, message: '请输入密码' }]} label="密码">
          <Input placeholder="请输入密码"/>
        </FormItem>
        <FormItem {...formTailLayout} name="hostname" rules={[{ required: true, message: '请输入IP' }]} label="IP">
          <Input placeholder="请输入IP"/>
        </FormItem>
        <FormItem {...formTailLayout} name="port" rules={[{ required: true, message: '请输入端口号' }]} label="端口号">
          <Input placeholder="请输入端口号"/>
        </FormItem>
        <FormItem {...formTailLayout} name="tenant" rules={[{ required: true, message: '请选择是否多租户' }]} label="多租户">
          <Radio.Group>
            <Radio.Button value="true">是</Radio.Button>
            <Radio.Button value="false">否</Radio.Button>
          </Radio.Group>
        </FormItem>
        <FormItem {...tailLayout}>
          <Button onClick={() => lookTableList(true)}>字段查看</Button>
          <Button style={{ marginLeft: 8 }} type="primary" htmlType="submit">保存</Button>
          <Button loading={asyncDbLoading} onClick={asyncDb} style={{ marginLeft: 8 }} type="primary" ghost>同步数据库到项目</Button>
        </FormItem>
      </Form>
      <TableList dbId={dbId} onClose={setVisible} visible={visible} />
    </>
  )
}

export default DatabaseConfigForm
